package com.ty.user.starter.util;

import com.alibaba.fastjson.JSON;
import com.ty.user.starter.constants.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class ResponseUtil {
    private ResponseUtil() {

    }

    public static <T> R<T> success() {
        R<T> res = new R<>();
        res.setCode(Constant.CODE_SUCCESS_MSG);
        return res;
    }

    public static <T> R<T> success(T t) {
        R<T> res = new R<>();
        res.setCode(Constant.CODE_SUCCESS_MSG);
        res.setData(t);
        return res;
    }

    public static <T> R<T> success(String msg, T t) {
        R<T> res = new R<>();
        res.setCode(Constant.CODE_SUCCESS_MSG);
        res.setMsg(msg);
        res.setData(t);
        return res;
    }

    public static <T> R<T> failed(int code, String msg) {
        R<T> res = new R<>();
        res.setCode(Constant.CODE_EXCEPTION);
        res.setMsg(msg);
        res.setCode(code);
        return res;
    }

    /**
     * 通过response直接发送
     *
     * @param response res
     * @param msg      消息内容
     * @param data     返回数据
     */
    public static <T> void writer(ServletResponse response, int code, String msg, T data) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = httpServletResponse.getWriter()) {
            R<T> res = new R<>();
            res.setMsg(msg);
            res.setCode(code);
            res.setData(data);
            out.append(JSON.toJSONString(res));
        } catch (IOException e) {
            log.error("返回Response信息失败" + e);
        }
    }
}
